/**
 * @author qiuny
 * @description 分组插件，用于合成分组和拆分分组
 * @class
 * @see {@link CoverEditor}
 */
import { fabric } from "fabric";
import { v4 as uuidV4 } from "uuid";

class GroupPlugin {
    static apis = ['group', 'unGroup']
    // static events = ["onAttributesChange"];
    constructor(canvas, editor) {
        this.canvas = canvas
        this.editor = editor
    }

    group() {
        const activeObject = this.isActiveObject()
        if (!activeObject) return
        // activeObject.toGroup: 将 activeSelection 更改为普通组，
        // 自动将其作为活动对象添加到画布的高级功能。没有触发任何事件。
        const activeGroup = activeObject.toGroup()
        const findObjectsByGroup = activeGroup.getObjects()
        activeGroup.clone(newGroup => {
            newGroup.set({ id: uuidV4(), name: '新的分组'})
            this.canvas.remove(activeGroup)
            findObjectsByGroup.forEach(item => {
                this.canvas.remove(item)
            })
            this.canvas.add(newGroup)
            this.canvas.setActiveObject(newGroup)
        })
    }

    unGroup() {
        const activeObject = this.isActiveObject()
        if (!activeObject) return
        // 当前获取对象是group图层，才能调用toActiveSelection方法
        // group.toActiveSelection():使某个组成为活动选择，从画布中删除该组
        activeObject.toActiveSelection()
        const findGroup = activeObject.getObjects()
        for(const item of findGroup) {
            item.set('id', uuidV4())
        }
        this.canvas.discardActiveObject().renderAll();
    }

    isActiveObject () {
        return this.canvas.getActiveObject()
    }

    destroy() {
        console.log('GroupPlugin destroy');
    }
}

export default GroupPlugin